package com.base.controller.api;

import com.base.helper.ApiinfoesHelper;
import com.base.po.acess.TokenUtils;
import com.base.po.param.NetState;
import com.base.po.voip.Apiinfoes;
import com.base.service.ApiinfoesService;
import com.base.utils.GsonUtil;
import com.base.utils.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/sign")
public class SignController {
	@Autowired
	private ApiinfoesService apiinfoesService;

	// 获取token
	@CrossOrigin
	@RequestMapping(value = "/getToken", method = RequestMethod.POST)
	public @ResponseBody NetState getToken(HttpServletRequest request, String Mobile, String ParentId)
			throws Exception {
		System.out.println(Mobile);
//		String AuthorizationToken = request.getHeader("SDB-Authorization");
//		System.out.println("SDB-Authorization"+AuthorizationToken);
		NetState netState = new NetState();
		// 判断参数
		if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
			netState.setData("参数异常");
			netState.setErrorCode(NetState.PARAMS_ERROR);
		} else {
			String encryptResult = TokenUtils.getToken(ParentId, Mobile);
			netState.setData(encryptResult);
			netState.setErrorCode(NetState.SUCCESS_CONN);
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "获取TOKEN");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, ParentId),
				GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 微信端 获取token
	@RequestMapping(value = "/wxGetToken", method = RequestMethod.POST)
	public @ResponseBody NetState wxGetToken(HttpServletRequest request, HttpServletResponse response,
			String Mobile, String ParentId)throws Exception {
		//微信端 跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
//		String AuthorizationToken = request.getHeader("SDB-Authorization");
//		System.out.println("SDB-Authorization"+AuthorizationToken);
		NetState netState = new NetState();
		// 判断参数
		if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
			netState.setData("参数异常");
			netState.setErrorCode(NetState.PARAMS_ERROR);
		} else {
			String encryptResult = TokenUtils.getToken(ParentId, Mobile);
			netState.setData(encryptResult);
			netState.setErrorCode(NetState.SUCCESS_CONN);
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "获取TOKEN");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, ParentId),
				GsonUtil.createJsonString(netState)));
		return netState;
	}
}
